"""
@Author    : ghenyar
@Time      : 2025/9/8 10:47
@File      : admin
@Desc      :  管理员路由
"""
from functools import partial

from fastapi import APIRouter, Security, Request, Query,Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.admin.decorator import log_operation
from app.admin.schemas.admin import AdminSchema
from app.admin.security import authority
from app.admin.service.admin_service import AdminService
from app.common.response import ApiResponse
from app.core.db import async_get_db

router = APIRouter()
title = "管理员"
# 鉴权
Auth = partial(Security, authority)


@router.get("/lists", dependencies=[Auth(scopes=["admin:list"])], response_model=ApiResponse)
async def admin_lit(request: Request, page: int = Query(1), pageSize: int = Query(10), key: str = Query(None),
                    status: int = Query(None),db: AsyncSession = Depends(async_get_db)):
    """
    管理员(账号)列表
    :param request: 请求体
    :param page: 当前页码
    :param pageSize: 每页显示条数
    :param key: 关键字
    :param status: 状态
    :param db: 数据库会话
    :return:
    """
    result = await AdminService.admin_lists(db,page, pageSize, key, status)
    return ApiResponse.page_list(result)


@router.post("/save", dependencies=[Auth(scopes=["admin:save"])], response_model=ApiResponse)
@log_operation(log_message=title, types=1)
async def admin_save(request: Request, admin_data: AdminSchema,db: AsyncSession = Depends(async_get_db)):
    """
    新增管理员
    :param request: 请求体
    :param admin_data: 管理员数据
    :param db: 数据库会话
    :return:
    """
    msg = "新增管理员"
    result = await AdminService.create_or_update(db,admin_data)
    if result:
        return ApiResponse.success(f"{msg}成功")
    else:
        return ApiResponse.failed(f"{msg}失败！")


@router.put("/save", dependencies=[Auth(scopes=["admin:edit"])], response_model=ApiResponse)
@log_operation(log_message=title, types=2)
async def admin_edit(request: Request, admin_data: AdminSchema,db: AsyncSession = Depends(async_get_db)):
    """
    编辑管理员
    :param request: 请求体
    :param admin_data: 管理员数据
    :param db: 数据库会话
    :return:
    """
    msg = "编辑管理员"
    result = await AdminService.create_or_update(db,admin_data)
    if result:
        return ApiResponse.success(f"{msg}成功")
    else:
        return ApiResponse.failed(f"{msg}失败！")


@router.delete("/delete/{admin_id}", dependencies=[Auth(scopes=["admin:delete"])], response_model=ApiResponse)
@log_operation(log_message=title, types=3)
async def admin_delete(request: Request, admin_id: int,db: AsyncSession = Depends(async_get_db)):
    """
    删除管理员(账号)
    :param request: 请求体
    :param admin_id: 管理员id
    :param db: 数据库会话
    :return:
    """
    result = await AdminService.del_admin(db,admin_id)
    msg = "删除管理员(账号)"
    if isinstance(result, bool) and result:
        return ApiResponse.success(f"{msg}成功")
    else:
        return ApiResponse.failed(f"{msg}失败！{result.get("message")}")

@router.put("/check_account", response_model=ApiResponse)
async def admin_check_account(request: Request,db: AsyncSession = Depends(async_get_db)):
    """
    检查账号
    :param request:
    :param db:
    :return:
    """
    data = await request.json()
    admin = await AdminService.get_admin_by_account(db,data.get("account").strip())
    flag = True if not admin or admin.id == data.get("id") else False
    msg = "当前账号可使用" if flag else "当前账号已存在，不可使用"
    return ApiResponse.result(data=flag, message=msg)
